package com.example.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.BaseProperties;
import com.example.pojo.SessionMessage;
import com.example.service.SessionMessageService;
import lombok.AllArgsConstructor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;
import java.util.List;


/**
 * 负责管理会话记忆
 */
@Component
@AllArgsConstructor
public class GlobalMemory implements ChatMemory {
    private final SessionMessageService sessionMessageService;
    @Override
    public void add(String conversationId, List<Message> messages) {
        sessionMessageService.addSession(conversationId, messages);
    }

    @Override
    public List<Message> get(String conversationId) {
        LambdaQueryWrapper<SessionMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SessionMessage::getSessionId, conversationId)
                .orderByAsc(SessionMessage::getCreateTime)
                .last("limit " + 20);
        List<SessionMessage> sessionMessageList = sessionMessageService.list(queryWrapper);
        return sessionMessageList.stream().map(BaseProperties::convertToMessage).flatMap(List::stream).toList();
    }
    @Override
    public void clear(String conversationId) {
        sessionMessageService.deleteSessionMessage(conversationId);
    }
}
